package com.wdh.kjs.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.wdh.kjs.R;
import com.wdh.kjs.data.SelectPictureUrl;
import com.wdh.kjs.http.Httpurl;
import com.wdh.kjs.http.response.MyCookieStore;
import com.wdh.kjs.model.JsonModel;
import com.wdh.kjs.model.JsonModel_my;
import com.wdh.kjs.util.ToastUtils;

import org.apache.http.impl.client.DefaultHttpClient;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.Locale;

/**
 * Created by CQH on 2016/4/21.
 */
public class RealNameAuthOrgActivity extends BaseTopActivity implements View.OnClickListener{

    public final static int  RESULTCODE_IdNumFile=15;
    public final static int  RESULTCODE_BusinessLicenseFile=16;
    public final static int RESULTCODE_PermitLicenseFile=17;

    private String idNumFilepath;
    private String businessLicenseFilepath;
    private String permitLicenseFilepath;

    private File idNumFile;
    private File businessLicenseFile;
    private File permitLicenseFile;

    private Intent intent;
    private LinearLayout bt_legalRepresentIDCard;
    private LinearLayout bt_businessLicense;
    private LinearLayout bt_openAccountLicence;
    private Button realName_org_submit;

    private String title="上传身份证";
    private String description="请上传身份证照片";

    private Context mContext = null;
    private String type = "";
    private String type_legalRepresentIDCard= "";
    private String type_businessLicense= "";
    private String type_openAccountLicence= "";
    private PopupWindow popwindow;
    private LinearLayout ll_pc_take_photo, ll_pc_pick_photo, ll_pc_cancel;

    private EditText EditText_oCompanyName;
    private EditText EditText_oUan;
    private EditText EditText_oRepresentName;
    private EditText EditText_oRepresentIdNum;
    private EditText EditText_oRepresentPhone;
  /*  private String oRepresentIdNumFile;
    private String oCompanyBusinessLicenseFile;
    private String oBankPermitLicenseFile;*/
    private String partyId;
    private JsonModel_my jsonModel_my;

    private String auditingOpinion="0";
    private String zhanghu;
    private String mima;
    private JsonModel jsonModel;
    private String url=Httpurl.URL_REALAUTH_ORG;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.real_name_auth_org);
        SharedPreferences sharedPreferences = getSharedPreferences("logininfo",MODE_PRIVATE);
        partyId = sharedPreferences.getString("loginToken", "");
        zhanghu = sharedPreferences.getString("zhanghao", "");
        mima = sharedPreferences.getString("mima", "");
        initTopBar("实名认证");
        initshimingorgnize();
        Intent intent1=getIntent();
        url=intent1.getStringExtra("URL");
        if("".equals(url)){
            url=Httpurl.URL_REALAUTH_ORG;
        }
        denglu();
        initview();
    }
    private void initshimingorgnize() {
        HttpUtils http = new HttpUtils();
        RequestParams params = new RequestParams();

//            params.addBodyParameter("emailAddress","742051747@qq.com" );
        params.addBodyParameter("partyId", partyId);

        http.send(HttpRequest.HttpMethod.POST, Httpurl.URL_HUOQURENZHENG_O, params, new RequestCallBack<String>() {

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {


                Gson gson = new Gson();
                jsonModel = gson.fromJson(responseInfo.result, JsonModel.class);
                if (jsonModel.success) {

                    auditingOpinion = jsonModel.getRealAuthInfo().getAuditingOpinion();

                }
            }

            @Override
            public void onFailure(HttpException error, String msg) {


            }
        });

    }
    private void loadData() {
        RequestParams params = new RequestParams();
        params.addBodyParameter("partyId", partyId);
        params.addBodyParameter("oCompanyName",EditText_oCompanyName.getText().toString());
        params.addBodyParameter("oUan",EditText_oUan.getText().toString());
        params.addBodyParameter("oRepresentName",EditText_oRepresentName.getText().toString());
        params.addBodyParameter("oRepresentIdNum",EditText_oRepresentIdNum.getText().toString());
        params.addBodyParameter("oRepresentPhone",EditText_oRepresentPhone.getText().toString());
        params.addBodyParameter("oRepresentIdNumFile",idNumFile);
        params.addBodyParameter("oCompanyBusinessLicenseFile",businessLicenseFile);
        params.addBodyParameter("oBankPermitLicenseFile",permitLicenseFile);

        HttpUtils http = new HttpUtils();
        http.configCookieStore(MyCookieStore.firstCookieStore);
        http.send(HttpRequest.HttpMethod.POST,url, params, new RequestCallBack<String>() {

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Gson gson = new Gson();
                jsonModel_my = gson.fromJson(responseInfo.result, JsonModel_my.class);

                Log.i("msg",partyId+EditText_oCompanyName.getText().toString()+"");
                Log.i("msg",responseInfo.result);

               // System.out.println("实名认证结果:"+responseInfo.result);

                if (jsonModel_my.success) {
                        Log.i("msg","realName_org_submit");
                    trueDialogShow(jsonModel_my.getMsg());
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            intent = new Intent();
                            SharedPreferences.Editor editor = getSharedPreferences("logininfo",MODE_PRIVATE).edit();
                            editor.putString("type","o");
//                            editor.putString("levels", "1");
                            if (!auditingOpinion.equals("0")) {
                                editor.putString("levels", "1");
                            }
                            editor.putString("nickName", EditText_oCompanyName.getText().toString());
                            editor.putString("faren", EditText_oRepresentPhone.getText().toString());
                            editor.putString("farenname", EditText_oRepresentName.getText().toString());

                            editor.commit();
                            finish();
                            intent.setClass(RealNameAuthOrgActivity.this, SecuritySetting.class);
                            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            startActivity(intent);
                        }
                    },2000);
            }else
                    ToastUtils.showShort(getApplicationContext(),"实名认证失败");
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                ToastUtils.showShort(getApplicationContext(), "网络异常！");
            }
        });

    }

    private void initview() {
        bt_legalRepresentIDCard = (LinearLayout) findViewById(R.id.bt_legalRepresentIDCard);
        bt_legalRepresentIDCard.setOnClickListener(this);

        bt_businessLicense = (LinearLayout) findViewById(R.id.bt_businessLicense);
        bt_businessLicense.setOnClickListener(this);

        bt_openAccountLicence = (LinearLayout) findViewById(R.id.bt_openAccountLicence);
        bt_openAccountLicence.setOnClickListener(this);

        realName_org_submit = (Button) findViewById(R.id.realName_org_submit);
        realName_org_submit.setOnClickListener(this);

        EditText_oCompanyName = (EditText)findViewById(R.id.EditText_oCompanyName);
        EditText_oUan = (EditText)findViewById(R.id.EditText_oUan);
        EditText_oRepresentName = (EditText)findViewById(R.id.EditText_oRepresentName);
        EditText_oRepresentIdNum = (EditText)findViewById(R.id.EditText_oRepresentIdNum);
        EditText_oRepresentPhone = (EditText)findViewById(R.id.EditText_oRepresentPhone);

    }

    private void trueDialogShow(String hint) {
        View dialog = (LinearLayout) getLayoutInflater().inflate(R.layout.view_dialog_true, null);
        TextView tv_dialog_false_hint = (TextView) dialog.findViewById(R.id.tv_dialog_true_hint);
        tv_dialog_false_hint.setText(hint);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(dialog);
        builder.create();
        final AlertDialog dialogShow = builder.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (resultCode){
            case RESULTCODE_IdNumFile:{
                idNumFilepath=data.getStringExtra("filepath");
                idNumFile=new File(idNumFilepath);
             //   System.out.println("身份证："+idNumFilepath);
                break;
            }
            case RESULTCODE_BusinessLicenseFile:{
                businessLicenseFilepath=data.getStringExtra("filepath");
              //  System.out.println("营业执照:"+businessLicenseFilepath);
                businessLicenseFile=new File(businessLicenseFilepath);
                break;
            }
            case RESULTCODE_PermitLicenseFile:{
                permitLicenseFilepath=data.getStringExtra("filepath");
              //  System.out.println("开户许可证"+permitLicenseFilepath);
                permitLicenseFile=new File(permitLicenseFilepath);
                break;
            }
            default:{
                break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    public void onClick(View v){
        switch (v.getId()) {
            case R.id.realName_org_submit:

                if (idNumFile!=null||businessLicenseFile!=null||permitLicenseFile!=null)
                loadData();
else
                    TipDialogShow("未上传附件");
                break;
            case R.id.bt_legalRepresentIDCard: {
                intent = new Intent(this, UploadIdCardActivity.class);
                title="上传身份证";
                description="请上传身份证照片";
                intent.putExtra("title",title);
                intent.putExtra("description",description);
                intent.putExtra("id","0");
                startActivityForResult(intent, RESULTCODE_IdNumFile);
                // startActivity(intent);
                break;
            }
            case R.id.bt_businessLicense:{
             //   intent = new Intent(this, UploadBussinessLicenesActivity.class);
                intent = new Intent(this, UploadIdCardActivity.class);
                title="上传营业执照";
                description="上传营业执照照片或扫描件";
                intent.putExtra("title",title);
                intent.putExtra("description",description);
                intent.putExtra("id","1");
                startActivityForResult(intent,RESULTCODE_BusinessLicenseFile);
                break;
                }
            case R.id.bt_openAccountLicence: {
               // intent = new Intent(this, UploadOpenAccountLicenesActivity.class);
                intent = new Intent(this, UploadIdCardActivity.class);
                title="上传开户许可证";
                description="请上传开户许可证照片或扫描件";
                intent.putExtra("title",title);
                intent.putExtra("description",description);
                intent.putExtra("id","2");
                startActivityForResult(intent,RESULTCODE_PermitLicenseFile);
                break;
            }
        }
    }

    private void denglu() {
        RequestParams params = new RequestParams();
        params.addBodyParameter("USERNAME", zhanghu);
        params.addBodyParameter("PASSWORD", mima);
        final HttpUtils http = new HttpUtils();
        http.send(HttpRequest.HttpMethod.POST, Httpurl.URL_LOGIN, params, new RequestCallBack<String>() {

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {

                Gson gson = new Gson();
                jsonModel = gson.fromJson(responseInfo.result, JsonModel.class);
                String m = jsonModel.getPartyId();
                if (jsonModel._LOGIN_PASSED_()) {
                    DefaultHttpClient zpf = (DefaultHttpClient) http.getHttpClient();
                    MyCookieStore.firstCookieStore = zpf.getCookieStore();
                    SharedPreferences.Editor editor = getSharedPreferences("logininfo", MODE_PRIVATE).edit();
                    editor.putString("loginToken", jsonModel.getPartyId());
                    editor.putString("nickName", jsonModel.getNickName());
                    editor.putString("phoneNumber", jsonModel.getPhoneNumber());
                    editor.putString("levels", jsonModel.getLevels());
                    editor.putString("type", jsonModel.getType());
                    editor.putString("zhanghao", zhanghu);
                    editor.putString("mima", mima);
                    editor.commit();
                }
            }
            @Override
            public void onFailure(HttpException error, String msg) {
            }
        });

    }
    private void TipDialogShow(String hint) {
        View dialog = View.inflate(this,R.layout.view_dialog_tip, null);
        Button bt_dialog_false_positive = (Button) dialog.findViewById(R.id.bt_dialog_false_positive);
        TextView tv_dialog_false_hint = (TextView) dialog.findViewById(R.id.tv_dialog_false_hint);
        tv_dialog_false_hint.setText(hint);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(dialog);
        builder.create();
        final AlertDialog dialogShow = builder.show();
        bt_dialog_false_positive.setOnClickListener(new android.view.View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialogShow.dismiss();
            }
        });
    }
}

